class stockAnalyseService:
    # 计算并插入周K、月K、年K
    def calculate_and_store_kline_data(kline_type: str):
        """
        根据日K数据计算指定类型的聚合K线数据（周K、月K、年K）
        """
        # 定义聚合周期
        if kline_type == "W":  # 周K
            group_by_format = "%Y-W%U"  # 按年和周分组
        elif kline_type == "M":  # 月K
            group_by_format = "%Y-%m"  # 按年和月分组
        elif kline_type == "Y":  # 年K
            group_by_format = "%Y"  # 按年分组
        else:
            raise ValueError("Invalid kline_type. Must be 'W', 'M', or 'Y'.")

        # 查询日K数据并进行聚合
        query = AntMonitorDay.select(
            AntMonitorDay.stock_code,
            fn.strftime(group_by_format, AntMonitorDay.trade_date).alias("period"),
            fn.MIN(AntMonitorDay.open).alias("open"),
            fn.MAX(AntMonitorDay.high).alias("high"),
            fn.MIN(AntMonitorDay.low).alias("low"),
            fn.MAX(AntMonitorDay.close).alias("close"),
            fn.SUM(AntMonitorDay.vol).alias("vol"),
            fn.SUM(AntMonitorDay.amount).alias("amount"),
        ).group_by(
            AntMonitorDay.stock_code,
            fn.strftime(group_by_format, AntMonitorDay.trade_date),
        )

        # 插入聚合数据
        with db.atomic():
            for row in query.dicts():
                KLineData.create(
                    stock_code=row["stock_code"],
                    trade_date=row["period"],
                    open=row["open"],
                    high=row["high"],
                    low=row["low"],
                    close=row["close"],
                    vol=row["vol"],
                    amount=row["amount"],
                    type=kline_type,
                )
